package cn.matezk.things.broker.client;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.things.broker.service.MqttAuthService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.dromara.mica.mqtt.codec.MqttQoS;
import org.dromara.mica.mqtt.spring.client.MqttClientSubscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 客户端消息监听
 *
 * @author L.cm
 */
@Service
public class MqttClientSubscribeListener {
	private static final Logger logger = LoggerFactory.getLogger(MqttClientSubscribeListener.class);

//	@Autowired
//	private ITencentService tencentService;
//	@Autowired
//	private IActionService actionService;
//	@Autowired
	private MqttAuthService mqttAuthService;
//	@Autowired
//	private IEmqxService emqxService;

	@MqttClientSubscribe(value = "$share/$queue/tencent/down/property/+/+", qos = MqttQoS.QOS0)
	public void subTencent(String topic, byte[] bytes) throws TencentCloudSDKException {
//		String payload = new String(bytes, StandardCharsets.UTF_8);
//		logger.info("topic:{} payload:{}", topic, payload);
//		String items[] = topic.split("/");
//		String productId = items[items.length - 2];
//		String deviceName = items[items.length - 1];
//		tencentService.control(productId, deviceName, payload);
	}

	@MqttClientSubscribe(value = "things/up/action/+/+", qos = MqttQoS.QOS0)
	public void subAction(String topic, byte[] bytes) {
//		String payload = new String(bytes, StandardCharsets.UTF_8);
//		logger.info("topic:{} payload:{}", topic, payload);
//		actionService.reply(new Date(), JSONUtil.parseObj(payload));
	}

	@MqttClientSubscribe(value = "$share/$queue/things/up/register/+/+", qos = MqttQoS.QOS0)
	public void subRegister(String topic, byte[] bytes) throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
		String payload = new String(bytes, StandardCharsets.UTF_8);
		logger.info("topic:{} payload:{}", topic, payload);
		JSONObject object = JSONUtil.parseObj(payload);
		JSONObject reply = mqttAuthService.register(object.getStr("productId"), object.getStr("deviceName"));
//		emqxService.publish(topic.replace("/up/", "/down/"), reply.toString());
	}
}